<?php 
include "./Lib/Common.php";
//---------= Start read schemal ----------------------------------------------------------------------------------------------
// database constants
// make sure the information is correct
define("DB_SERVER", DATABASE_HOST);
define("DB_USER", DATABASE_USER);
define("DB_PASS", DATABASE_PASSWORD);
define("DB_NAME", DATABASE_NAME);

// connection to the database
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
   or die("Unable to connect to MySQL");

// select a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
   or die("Could not select examples");

// return all available tables 
$result_tbl = mysql_query( "SHOW TABLES FROM ".DB_NAME, $dbhandle );

$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
   $tables[] = $row[0];
}

$arrTable = array();
$i = 0;
foreach ( $tables as $table ) {
   $result_fld = mysql_query( "SHOW FIELDS FROM ".$table, $dbhandle );
   $arrTable[$i]["TableName"] = $table;
   while( $row1 = mysql_fetch_row($result_fld) ) {
	  if ($row1[3] == "PRI") { // PrimaryKey
	  	$arrTable[$i]["PrimaryKey"] = $row1[0];
		$arrTable[$i][] = $row1[0];
	  } else $arrTable[$i][] = $row1[0];
	  
   }
   $i++;
}

mysql_close($dbhandle);
// ============= End of read schema ============================================================================================
//---------= Start create Entities and DAL -------------------------------------------------------------------------------------
//$arrTable = array();
//$arrTable[] = array("TableName"=>"users", "PrimaryKey"=>"UserID", "UserID", "Username", "Fullname", "Password", "UserType");
//$arrTable[] = array("TableName"=>"allfields", "PrimaryKey"=>"ID", "ID", "FVarchar", "FNumeric", "FDate");

for ($i=0; $i<count($arrTable); $i++) {
	$table = $arrTable[$i];
	// Create Entity
	unset($handle);
	$handle = fopen("./Entities/".$table["TableName"]."Obj.php", "w");

	$variables = GetVariableContent($table);
	$initFuncs = GetInitFunctions($table);
	fwrite($handle, "<?php \nclass ".$table["TableName"]."Obj \n{".$variables."\n".$initFuncs."\n} \n?>");

	fclose($handle);

	// Create DAL
	unset($handle);
	$handle = fopen("./DAL/".$table["TableName"]."DAL.php", "w");

	$insertFunc = GetInsertFunction($table);
	$updateFunc = GetUpdateFunction($table);
	$loadFunc	= GetLoadFunction($table);
	$existFunc	= GetExistFunction($table) ;
	$deleteFunc = GetDeleteFunction($table) ;
	$getlistFunc= GetListFunction($table);
	$pushFunc	= GetPushFunction($table);
	$popFunc	= GetPopFunction($table);

	fwrite($handle, "<?php \nclass ".$table["TableName"]."DAL \n{\n".$insertFunc."\n".$updateFunc."\n".$loadFunc."\n".$existFunc."\n".
		$deleteFunc."\n".$getlistFunc."\n".$pushFunc."\n".$popFunc."\n} \n?>");

	fclose($handle);
}
echo "Database library have been created.";
function GetVariableContent($table) 
{
	$variableContent = "";
	for ($i=0; $i<count($table)-2; $i++) 				
		$variableContent = $variableContent."\n\tvar \$".$table[$i].";";	
	$variableContent = $variableContent."\n\tvar \$otherFields;";	
	return $variableContent;
}

function GetInitFunctions($table) 
{
	$initFunc = "\n\tfunction ".$table["TableName"]."Obj (";
	$initFuncContent = "";
	$funcContent = "\n\tpublic function TableName() { return \"".$table["TableName"]."\";}";
	for ($i=0; $i<count($table)-2; $i++) {			
		$funcContent = $funcContent."\n\tpublic function ".$table[$i]."FieldName() { return \"".$table[$i]."\";}";	
		$comma = ($i<=0?"":",");
		$initFunc = $initFunc.$comma."\$p".$table[$i]."=\"\"";
		$initFuncContent = $initFuncContent."\n\t\t\$this->".$table[$i]." = \$p".$table[$i].";";
	}
	$initFunc = $initFunc.") {\n".$initFuncContent."\n\t}\n";
	return $funcContent."\n".$initFunc;
}

function GetInsertFunction ($table) 
{
	$fields = "";
	$values = "";
	for ($i=1; $i<count($table)-2; $i++) {
		$fields = $fields.($fields==""?"":", ").$table[$i];
		$values = $values.($values==""?"":", ")."\".ToSQLPostVAL(\$".$table["TableName"]."Obj->".$table[$i].").\"";
	}
	$strFunc = "".
		"\tpublic function Insert(\$db, \$".$table["TableName"]."Obj, &\$errorMsg) \n\t{\n".
			"\t\t\$errorMsg = \"\";\n\n".
			"\t\t\$query = \"INSERT INTO ".$table["TableName"]." (".$fields.") VALUES (".$values.")\";\n".
			"\t\tif (!\$db->query(\$query)) {\n".
				"\t\t\t\$errorMsg = mysql_error().\" Query: \$query.\";\n".
				"\t\t\treturn false;\n".
			"\t\t}\n\n".
			"\t\t\$".$table["TableName"]."Obj->".$table["PrimaryKey"]." = mysql_insert_id();\n".
			"\t\treturn true;\n".
		"\t}\n";

	return $strFunc;
}

function GetUpdateFunction($table) 
{
	$setFieldValues = "";
	for ($i=1; $i<count($table)-2; $i++) {
		$setFieldValues = $setFieldValues.($setFieldValues==""?"":", ").$table[$i]."=\".ToSQLPostVAL($".$table["TableName"]."Obj->".$table[$i].").\"";
	}
	$strFunc = "".
		"\tpublic function Update(\$db, \$".$table["TableName"]."Obj, &\$errorMsg)\n\t {	\n".
			"\t\t\$errorMsg = \"\";\n\n".	

			"\t\t\$query = \"UPDATE ".$table["TableName"]." SET ".$setFieldValues." WHERE ".$table["PrimaryKey"]."=\".ToSQLPostVAL(\$".$table["TableName"]."Obj->".$table["PrimaryKey"].");\n".
			"\t\tif (!\$db->query(\$query)) {\n".
				"\t\t\t\$errorMsg = mysql_error().\" Query: \$query.\";\n".
				"\t\t\treturn false;\n".
			"\t\t}\n\n".
			"\t\treturn true;\n".
		"\t}\n";
	return $strFunc;
}

function GetLoadFunction($table) 
{
	$newValues = "";
	for ($i=0; $i<count($table)-2; $i++) {
		$newValues = $newValues.($newValues==""?"":", ")."\$db->f(\"".$table[$i]."\")";
	}

	$strFunc = "".
		"\tpublic function Load(\$db, \$id, &\$errorMsg, \$joinTables=\"\", \$onFields=\"\", \$getFields=\"\")\n\t{\n".
			"\t\t\$errorMsg = \"\";\n".	
			"\t\t\$joinClause = \"\";\n".	
			"\t\t\$extraFields = \"\";\n".	
			"\t\tfor (\$i=0; is_array(\$joinTables) && \$i<count(\$joinTables); \$i++)\n".
			"\t\t{\n".
				"\t\t\t\$joinClause .= \" LEFT JOIN \".\$joinTables[\$i].\" \".\$joinTables[\$i].\" ON \".\$onFields[\$i];\n".	
				"\t\t\t\$fields = explode(\",\", \$getFields[\$i]);\n".	
				"\t\t\tfor (\$j=0; \$j<count(\$fields); \$j++)\n".	
					"\t\t\t\t\$extraFields .= \", \".\$joinTables[\$i].\".\".\$fields[\$j].\" AS \".\$joinTables[\$i].\"_\".\$fields[\$j];\n".	
			"\t\t}\n".	
			"\t\t\$query	= \"SELECT ".$table["TableName"].".*\$extraFields FROM ".$table["TableName"]." \$joinClause WHERE ".$table["TableName"].".".$table["PrimaryKey"]."=\".ToSQLPostVAL(\$id);\n\n".		

			"\t\tif (!\$db->query(\$query)) {\n".		
				"\t\t\t\$errorMsg	= mysql_error().\" Query: \$query.\";\n".		
				"\t\t\treturn null;\n".
			"\t\t} else {\n".		
				"\t\t\tif (\$db->next_record()) {\n".	
					"\t\t\t\t\$".$table["TableName"]."Obj = new ".$table["TableName"]."Obj(".$newValues.");\n".
					"\t\t\t\tfor (\$i=0; is_array(\$joinTables) && \$i<count(\$joinTables); \$i++)\n".
					"\t\t\t\t{\n".
						"\t\t\t\t\t\$fields = explode(\",\", \$getFields[\$i]);\n".
						"\t\t\t\t\tfor (\$j=0; \$j<count(\$fields); \$j++)\n".
						"\t\t\t\t\t{\n".
							"\t\t\t\t\t\t\$categorieschildObj->otherFields[\$joinTables[\$i].\"_\".\$fields[\$j]] = \$db->f(\$joinTables[\$i].\"_\".\$fields[\$j]);\n".
						"\t\t\t\t\t}\n".
					"\t\t\t\t}\n".
					"\t\t\t\treturn \$".$table["TableName"]."Obj;\n".
				"\t\t\t} else {\n".
					"\t\t\t\t\$errorMsg = \"Data not found.\";\n".
					"\t\t\t\treturn null;\n".
				"\t\t\t}\n".
			"\t\t}\n".
			"\t\treturn null;\n".
		"\t}\n";
		
		return $strFunc;
}

function GetExistFunction($table) 
{
	$strFunc = "".
		"\tpublic function IsExist(\$db, \$whereStr) \n\t{\n".
			"\t\t\$query	= \"SELECT * FROM ".$table["TableName"]."\";\n\n".		
			
			"\t\tif (\$whereStr!=\"\") \$query = \$query.\" WHERE \".\$whereStr;\n".
			"\t\telse return false;\n\n".

			"\t\tif (!\$db->query(\$query)) {\n".		
				"\t\t\treturn false;\n".	
			"\t\t} else {\n".		
				"\t\t\twhile (\$db->next_record()) {\n".
					"\t\t\t\treturn true;\n".
				"\t\t\t}\n".
			"\t\t}\n".	
			"\t\treturn false;\n".
		"\t}\n";
	
	return $strFunc;
}

function GetDeleteFunction($table) 
{
	$strFunc = "".
		"\tpublic function Pure(\$db, \$whereStr, &\$errorMsg) \n\t{\n".
			"\t\t\$query	= \"DELETE FROM ".$table["TableName"]."\";\n\n".		
			
			"\t\tif (\$whereStr!=\"\") \$query = \$query.\" WHERE \".\$whereStr;\n".
			"\t\telse {\n".
					"\t\t\t\$errorMsg = \"You have no delete condition in query string (\$query WHERE ?).\";\n".
					"\t\t\treturn false;\n".
				"\t\t}\n\n".


			"\t\tif (!\$db->query(\$query)) {\n".		
					"\t\t\t\$errorMsg = mysql_error().\" Query: \$query.\";\n".		
					"\t\t\treturn false;\n".
			"\t\t}\n".	
			"\t\treturn true;\n".
		"\t}\n";
	
	return $strFunc;
}

function GetListFunction($table) 
{
	$newValues = "";
	for ($i=0; $i<count($table)-2; $i++) {
		$newValues = $newValues.($newValues==""?"":", ")."\$db->f(\"".$table[$i]."\")";
	}

	$strFunc = "".
		"\tpublic function GetList(\$db, \$whereStr, \$orderByStr, \$limit, &\$errorMsg, \$joinTables=\"\", \$onFields=\"\", \$getFields=\"\") \n\t{\n".
			"\t\t\$returnData = array();\n".
			"\t\t\$joinClause = \"\";\n".	
			"\t\t\$extraFields = \"\";\n".	
			"\t\tfor (\$i=0; is_array(\$joinTables) && \$i<count(\$joinTables); \$i++)\n".
			"\t\t{\n".
				"\t\t\t\$joinClause .= \" LEFT JOIN \".\$joinTables[\$i].\" \".\$joinTables[\$i].\" ON \".\$onFields[\$i];\n".	
				"\t\t\t\$fields = explode(\",\", \$getFields[\$i]);\n".	
				"\t\t\tfor (\$j=0; \$j<count(\$fields); \$j++)\n".	
					"\t\t\t\t\$extraFields .= \", \".\$joinTables[\$i].\".\".\$fields[\$j].\" AS \".\$joinTables[\$i].\"_\".\$fields[\$j];\n".	
			"\t\t}\n".	
			"\t\t\$errorMsg = \"\";\n".	
			"\t\t\$query	= \"SELECT ".$table["TableName"].".*\$extraFields FROM ".$table["TableName"]."\$joinClause\";\n\n".		
			
			"\t\tif (\$whereStr!=\"\") \$query = \$query.\" WHERE \".\$whereStr;\n".
			"\t\tif (\$orderByStr!=\"\") \$query = \$query.\" ORDER BY \".\$orderByStr;\n".
			"\t\tif (\$limit!=\"\") \$query = \$query.\" LIMIT \".\$limit;\n\n".

			"\t\tif (!\$db->query(\$query)) {\n".		
				"\t\t\t\$errorMsg	= mysql_error().\" Query: \$query.\";\n".		
			"\t\t} else {\n".		
				"\t\t\twhile (\$db->next_record()) 	{\n".
					"\t\t\t\t\$objVal = new ".$table["TableName"]."Obj(".$newValues.");\n".
					"\t\t\t\tfor (\$i=0; is_array(\$joinTables) && \$i<count(\$joinTables); \$i++)\n".
					"\t\t\t\t{\n".
						"\t\t\t\t\t\$fields = explode(\",\", \$getFields[\$i]);\n".
						"\t\t\t\t\tfor (\$j=0; \$j<count(\$fields); \$j++)\n".
						"\t\t\t\t\t{\n".
							"\t\t\t\t\t\t\$objVal->otherFields[\$joinTables[\$i].\"_\".\$fields[\$j]] = \$db->f(\$joinTables[\$i].\"_\".\$fields[\$j]);\n".
						"\t\t\t\t\t}\n".
					"\t\t\t\t}\n".
					"\t\t\t\t\$returnData[] = \$objVal;\n".
				"\t\t\t}\n".
			"\t\t}\n".	
			"\t\treturn \$returnData;\n".
		"\t}\n";	
	return $strFunc;
}
function GetPopFunction($table) 
{
	$globalVars = "";
	$pushVars = "";
	for ($i=0; $i<count($table)-2; $i++) {
		$globalVars = $globalVars.($globalVars==""?"":", ")."\$".$table[$i];
		$pushVars = $pushVars.($pushVars==""?"\t\t":"\n\t\t")."if (isset(\$".$table[$i].")) \$".
							$table["TableName"]."Obj->".$table[$i]." = \$".$table[$i].";";
	}

	$strFunc = "".
		"\tpublic function Pop(&\$".$table["TableName"]."Obj)\n\t{\n".
			"\t\tglobal ".$globalVars.";\n\n".

			$pushVars."\n".
		"\t}\n";
	return $strFunc;
}
function GetPushFunction($table) 
{
	$globalVars = "";
	$pushVars = "";
	for ($i=0; $i<count($table)-2; $i++) {
		$globalVars = $globalVars.($globalVars==""?"":", ")."\$".$table[$i];
		$pushVars = $pushVars.($pushVars==""?"\t\t":"\n\t\t")."\$".
							$table[$i]." = \$".$table["TableName"]."Obj->".$table[$i].";";
	}

	$strFunc = "".
		"\tpublic function Push(\$".$table["TableName"]."Obj)\n\t{\n".
			"\t\tglobal ".$globalVars.";\n\n".

			$pushVars."\n".
		"\t}\n";
	return $strFunc;
}
?>